package Back;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.List;
import Dao.dt;

public class ReplaySelectorFrame extends JFrame {

    private dt dao;

    public ReplaySelectorFrame() {
        super("回放选择器");
        initializeUI();
        connectToDatabase();
        loadReplayNames();
    }

    private void initializeUI() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 600);
        setLayout(null); // 使用绝对布局（可考虑改用布局管理器）
    }

    private void connectToDatabase() {
        dao = new dt();
        dao.connect();
    }

    private void loadReplayNames() {
        List<String> replayNames = dao.getReplayNames();

        // 创建下拉框
        JComboBox<String> replayComboBox = new JComboBox<>(replayNames.toArray(new String[0]));
        replayComboBox.setBounds(0, 25, 150, 30);
        add(replayComboBox);

        // 播放按钮
        JButton playButton = new JButton("播放选中回放");
        playButton.setBounds(170, 25, 120, 30);
        playButton.addActionListener(e -> {
            String selectedName = (String) replayComboBox.getSelectedItem();
            if (selectedName != null) {
                MAP mapData = dao.getnewmap(selectedName);
                mapData.allpath = dao.createCarPathArray(selectedName, mapData.carcount, mapData.max_time);
                if (mapData != null) {
                    ReplayPanel replayPanel = new ReplayPanel(mapData);
                    JFrame replayFrame = new JFrame("回放：" + selectedName);
                    replayFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                    replayFrame.setSize(800, 800);
                    replayFrame.add(replayPanel, BorderLayout.CENTER);
                    replayFrame.setVisible(true);
                }
            }
        });
        add(playButton);
    }

    // 窗口关闭时关闭数据库连接
    public void setupCloseOperation() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosed(WindowEvent e) {
                if (dao != null) {
                    dao.closeConnection();
                }
            }
        });
    }

    // 主方法可以直接运行该窗口
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ReplaySelectorFrame frame = new ReplaySelectorFrame();
            frame.setVisible(true);
        });
    }
}
